package cfca.seal.front.service.servlet;

import cfca.sadk.util.Base64;
import cfca.seal.front.service.FunctionType;
import cfca.seal.front.service.ws.IPdfSealService;
import cfca.seal.util.StringUtil;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class PdfSealServlet extends HttpServlet
{
  private static final long serialVersionUID = -2802334706155081655L;
  private static final Logger logger = LoggerFactory.getLogger("service_sys");

  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    request.setCharacterEncoding("UTF-8");
    String type = request.getParameter("type");
    OutputStream os = response.getOutputStream();
    try {
      ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
      IPdfSealService pdfSealService = (IPdfSealService)applicationContext.getBean("pdfSealServiceImpl");

      if (type.equals(FunctionType.sealAutoPdf.toString()))
      {
        String pdfString = request.getParameter("pdf");
        byte[] pdf = "".getBytes("UTF-8");
        if (StringUtil.isNotEmpty(pdfString)) {
          pdf = Base64.decode(pdfString.getBytes("UTF-8"));
        }
        String sealStrategyXML = request.getParameter("sealStrategyXML");
        if (StringUtil.isNotEmpty(sealStrategyXML)) {
          sealStrategyXML = new String(Base64.decode(sealStrategyXML.getBytes("UTF-8")), "UTF-8");
        }
        byte[] sealAutoPdf = pdfSealService.sealAutoPdf(pdf, sealStrategyXML);
        byte[] result = Base64.encode(sealAutoPdf);
        os.write(result, 0, result.length);
      } else if (type.equals(FunctionType.verifyPdfSeal.toString()))
      {
        String pdfString = request.getParameter("sealedPdf");
        byte[] sealedPdfFile = "".getBytes("UTF-8");
        if (StringUtil.isNotEmpty(pdfString)) {
          sealedPdfFile = Base64.decode(pdfString.getBytes("UTF-8"));
        }
        String verifyStrategyXML = request.getParameter("verifyStrategyXML");
        if (StringUtil.isNotEmpty(verifyStrategyXML)) {
          verifyStrategyXML = new String(Base64.decode(verifyStrategyXML.getBytes("UTF-8")), "UTF-8");
        }
        String verifyPdfSeal = pdfSealService.verifyPdfSeal(sealedPdfFile, verifyStrategyXML);
        byte[] result = Base64.encode(verifyPdfSeal.getBytes("UTF-8"));
        os.write(result, 0, result.length);
      } else if (type.equals(FunctionType.sealAutoCrossPdf.toString()))
      {
        String pdfString = request.getParameter("pdf");
        byte[] pdf = "".getBytes("UTF-8");
        if (StringUtil.isNotEmpty(pdfString)) {
          pdf = Base64.decode(pdfString.getBytes("UTF-8"));
        }
        String crossSealStrategyXML = request.getParameter("crossSealStrategyXML");
        if (StringUtil.isNotEmpty(crossSealStrategyXML)) {
          crossSealStrategyXML = new String(Base64.decode(crossSealStrategyXML.getBytes("UTF-8")), "UTF-8");
        }
        byte[] sealAutoCrossPdf = pdfSealService.sealAutoCrossPdf(pdf, crossSealStrategyXML);
        byte[] result = Base64.encode(sealAutoCrossPdf);
        os.write(result, 0, result.length);
      } else if (type.equals(FunctionType.addWaterMark2Pdf.toString()))
      {
        String pdfString = request.getParameter("pdf");
        byte[] pdf = "".getBytes("UTF-8");
        if (StringUtil.isNotEmpty(pdfString)) {
          pdf = Base64.decode(pdfString.getBytes("UTF-8"));
        }
        String waterMarkStrategyXML = request.getParameter("waterMarkStrategyXML");
        if (StringUtil.isNotEmpty(waterMarkStrategyXML)) {
          waterMarkStrategyXML = new String(Base64.decode(waterMarkStrategyXML.getBytes("UTF-8")), "UTF-8");
        }
        byte[] addWaterMark2Pdf = pdfSealService.addWaterMark2Pdf(pdf, waterMarkStrategyXML);
        byte[] result = Base64.encode(addWaterMark2Pdf);
        os.write(result, 0, result.length);
      } else if (type.equals(FunctionType.batchSealAutoPdf.toString()))
      {
        String pdfString = request.getParameter("pdf");
        byte[] pdf = "".getBytes("UTF-8");
        if (StringUtil.isNotEmpty(pdfString)) {
          pdf = Base64.decode(pdfString.getBytes("UTF-8"));
        }
        String batchSealStrategyXML = request.getParameter("batchSealStrategyXML");
        if (StringUtil.isNotEmpty(batchSealStrategyXML)) {
          batchSealStrategyXML = new String(Base64.decode(batchSealStrategyXML.getBytes("UTF-8")), "UTF-8");
        }
        byte[] batchSealAutoPdf = pdfSealService.batchSealAutoPdf(pdf, batchSealStrategyXML);
        byte[] result = Base64.encode(batchSealAutoPdf);
        os.write(result, 0, result.length);
      } else if (type.equals(FunctionType.sealBase64PdfFunction.toString()))
      {
        String pdfBase64 = request.getParameter("pdfBase64");
        if (StringUtil.isNotEmpty(pdfBase64)) {
          pdfBase64 = new String(Base64.decode(pdfBase64.getBytes("UTF-8")), "UTF-8");
        }
        String pfxBase64 = request.getParameter("pfxBase64");
        if (StringUtil.isNotEmpty(pfxBase64)) {
          pfxBase64 = new String(Base64.decode(pfxBase64.getBytes("UTF-8")), "UTF-8");
        }
        String pfxPassword = request.getParameter("pfxPassword");
        if (StringUtil.isNotEmpty(pfxPassword)) {
          pfxPassword = new String(Base64.decode(pfxPassword.getBytes("UTF-8")), "UTF-8");
        }
        String imageBase64 = request.getParameter("imageBase64");
        if (StringUtil.isNotEmpty(imageBase64)) {
          imageBase64 = new String(Base64.decode(imageBase64.getBytes("UTF-8")), "UTF-8");
        }
        String sealFunctionStrategyXML = request.getParameter("sealFunctionStrategyXML");
        if (StringUtil.isNotEmpty(sealFunctionStrategyXML)) {
          sealFunctionStrategyXML = new String(Base64.decode(sealFunctionStrategyXML.getBytes("UTF-8")), "UTF-8");
        }
        String sealBase64PdfFunction = pdfSealService.sealBase64PdfFunction(pdfBase64, pfxBase64, pfxPassword, imageBase64, sealFunctionStrategyXML);
        byte[] result = sealBase64PdfFunction.getBytes("UTF-8");
        os.write(result, 0, result.length);
      } else if (type.equals(FunctionType.sealPdfFunction.toString()))
      {
        String pdfString = request.getParameter("pdf");
        byte[] pdf = "".getBytes("UTF-8");
        if (StringUtil.isNotEmpty(pdfString)) {
          pdf = Base64.decode(pdfString.getBytes("UTF-8"));
        }
        String pfxString = request.getParameter("pfx");
        byte[] pfx = "".getBytes("UTF-8");
        if (StringUtil.isNotEmpty(pfxString)) {
          pfx = Base64.decode(pfxString.getBytes("UTF-8"));
        }
        String pfxPassword = request.getParameter("pfxPassword");
        if (StringUtil.isNotEmpty(pfxPassword)) {
          pfxPassword = new String(Base64.decode(pfxPassword.getBytes("UTF-8")), "UTF-8");
        }
        String imageString = request.getParameter("image");
        byte[] image = "".getBytes("UTF-8");
        if (StringUtil.isNotEmpty(imageString)) {
          image = Base64.decode(imageString.getBytes("UTF-8"));
        }
        String sealFunctionStrategyXML = request.getParameter("sealFunctionStrategyXML");
        if (StringUtil.isNotEmpty(sealFunctionStrategyXML)) {
          sealFunctionStrategyXML = new String(Base64.decode(sealFunctionStrategyXML.getBytes("UTF-8")), "UTF-8");
        }
        byte[] sealPdfFunction = pdfSealService.sealPdfFunction(pdf, pfx, pfxPassword, image, sealFunctionStrategyXML);
        byte[] result = Base64.encode(sealPdfFunction);
        os.write(result, 0, result.length);
      } else if (type.equals(FunctionType.autoCalculatePdfHash.toString()))
      {
        String pdfString = request.getParameter("pdf");
        byte[] pdf = "".getBytes("UTF-8");
        if (StringUtil.isNotEmpty(pdfString)) {
          pdf = Base64.decode(formatMessage(pdfString).getBytes("UTF-8"));
        }
        String x509CertString = request.getParameter("x509Cert");
        byte[] x509Cert = "".getBytes("UTF-8");
        if (StringUtil.isNotEmpty(x509CertString)) {
          x509Cert = Base64.decode(formatMessage(x509CertString).getBytes("UTF-8"));
        }
        String strategyXML = request.getParameter("strategyXML");
        if (StringUtil.isNotEmpty(strategyXML)) {
          strategyXML = new String(Base64.decode(formatMessage(strategyXML).getBytes("UTF-8")), "UTF-8");
        }
        String autoCalculatePdfHash = pdfSealService.autoCalculatePdfHash(pdf, x509Cert, strategyXML);
        byte[] result = Base64.encode(autoCalculatePdfHash.getBytes("UTF-8"));
        os.write(result, 0, result.length);
      } else if (type.equals(FunctionType.synthesizeOuterSignature.toString()))
      {
        String signatureString = request.getParameter("signature");
        byte[] signature = "".getBytes("UTF-8");
        if (StringUtil.isNotEmpty(signatureString)) {
          signature = formatMessage(signatureString).getBytes("UTF-8");
        }
        String id = request.getParameter("id");
        if (StringUtil.isNotEmpty(id)) {
          id = new String(Base64.decode(formatMessage(id).getBytes("UTF-8")), "UTF-8");
        }
        byte[] synthesizeOuterSignature = pdfSealService.synthesizeOuterSignature(signature, id);
        byte[] result = Base64.encode(synthesizeOuterSignature);
        os.write(result, 0, result.length);
      }

      if (null != os) {
        os.flush();
        os.close();
      }
    }
    catch (Exception e)
    {
      logger.error("C0001", e);
      StringBuilder result = new StringBuilder();
      result.append("<Error><errorCode>");
      result.append("C0001");
      result.append("</errorCode><ErrorMessage>");
      result.append("错误");
      result.append("</ErrorMessage>");
      byte[] returnValue = Base64.encode(result.toString().getBytes("UTF-8"));
      os.write(returnValue, 0, returnValue.length);

      if (null != os) {
        os.flush();
        os.close();
      }
    }
    finally
    {
      if (null != os) {
        os.flush();
        os.close();
      }
    }
  }

  public String formatMessage(String msg) {
    return msg.replaceAll("%2B", "+").replaceAll("%2F", "/").replaceAll("%3D", "=").replaceAll("\n", "");
  }
}